Using module_function in Ruby modules can make the code’s intent less clear compared to extend self.
When you want to create a module with methods that can be called directly on the module itself, Ruby provides two main approaches:
module_function and extend self. While both work, they have different behaviors and implications.
module_function creates both private instance methods and public module methods. This dual nature can be confusing because it suggests
the module might be included in classes, when often the intent is just to have module-level utility methods.
extend self is more explicit about the intent. It clearly states that the module is extending itself with its own instance methods,
making them available as module methods. This approach is more straightforward when all methods in the module should be callable at the module
level.
The extend self approach is also more consistent with Ruby’s object model and is recommended by major style guides, including
Shopify’s Ruby Style Guide.
What is the potential impact?
Using module_function instead of extend self reduces code clarity and can make the module’s intended usage less obvious
to other developers. While functionally equivalent in many cases, extend self better communicates the intent when creating utility
modules with module-level methods.